<template>
  <el-container class="dict-manage-container" style="height: 100%;">
    <el-aside :width="dictTypeWidth + 'px'" class="dict-type-list" style="position: relative;">
      <!-- 左侧内容保持不变 -->
      <div class="dict-type-list-header">
        <span class="dict-type-title">字典类型</span>
        <el-button size="small" type="primary" @click="showTypeDialog('add')" class="icon-button">
          <el-icon><Plus /></el-icon>
        </el-button>
        <el-button size="small" type="success" @click="handleExportDictTypesExcel" class="icon-button" style="margin-left: 8px;">
          <el-icon><Download /></el-icon>
        </el-button>
      </div>
      <el-input v-model="typeSearch" placeholder="搜索类型" size="small" clearable class="dict-type-search" />
      <el-scrollbar style="height: 70vh;">
        <el-menu :default-active="selectedTypeCode" @select="handleTypeSelect" class="dict-type-menu" style="border: none;">
          <template v-if="pagedTypes.length > 0">
            <el-menu-item v-for="type in pagedTypes" :key="type.code" :index="type.code" :class="['dict-type-item', { 'is-active': selectedTypeCode === type.code }]">
              <span class="dict-type-name">{{ type.name }}<span class="dict-type-code">（{{ type.code }}）</span></span>
              <span class="dict-type-actions">
                <el-button size="small" type="text" @click.stop="showTypeDialog('edit', type)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button size="small" type="text" @click.stop="deleteType(type)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </span>
            </el-menu-item>
          </template>
          <template v-else>
            <div class="dict-type-empty">暂无字典类型</div>
          </template>
        </el-menu>
      </el-scrollbar>
      <el-pagination
        v-if="typeTotal > typePageSize"
        background
        layout="prev, pager, next"
        :page-size="typePageSize"
        :total="typeTotal"
        v-model:current-page="typeCurrentPage"
        class="dict-type-pagination"
        small
      />
      <!-- 拖动分隔条 -->
      <div class="drag-bar" @mousedown="startDrag"></div>
    </el-aside>
    <el-main class="dict-item-list-container">
      <!-- 右侧内容保持不变 -->
      <div class="header">
        <h2>字典项（{{ selectedTypeName }}）</h2>
        <div class="header-buttons">
          <el-button type="primary" :disabled="!selectedTypeCode" @click="showItemDialog('add')">
            <el-icon style="vertical-align: -2px;"><Plus /></el-icon>
            <span>新增</span>
          </el-button>
          <el-button type="success" :disabled="!selectedTypeCode" @click="handleExportDictItemsExcel" class="icon-button" style="margin-left: 8px;">
            <el-icon><Download /></el-icon>
            <span style="margin-left: 2px;">导出Excel</span>
          </el-button>
          <el-button type="warning" @click="handleExportAllDictItemsExcel" class="icon-button" style="margin-left: 8px;">
            <el-icon><Download /></el-icon>
            <span style="margin-left: 2px;">导出全部字典项</span>
          </el-button>
        </div>
      </div>
      <el-table :data="pagedItemList" v-loading="itemLoading" style="width: 100%; margin-bottom: 20px;" size="small">
        <el-table-column prop="label" label="显示文本" min-width="120" />
        <el-table-column prop="value" label="选项值" min-width="100" />
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120" />
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button size="small" type="primary" @click="showItemDialog('edit', scope.row)">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button size="small" type="danger" @click="deleteItem(scope.row)">
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="itemCurrentPage"
          v-model:page-size="itemPageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="itemTotal"
          @size-change="handleItemSizeChange"
          @current-change="handleItemCurrentChange"
        />
      </div>
      <!-- 其余弹窗等内容保持不变 -->
      <el-dialog v-model="typeDialogVisible" :title="typeDialogType==='add'?'新增类型':'编辑类型'" :width="'80%'" style="max-width: 1200px">
        <el-form :model="typeForm" :rules="typeRules" ref="typeFormRef" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="编码" prop="code">
                <el-input v-model="typeForm.code" :disabled="typeDialogType==='edit'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="typeForm.name" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
             <el-col :span="24">
              <el-form-item label="描述" prop="description">
                <el-input v-model="typeForm.description" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="typeDialogVisible=false">取消</el-button>
          <el-button type="primary" @click="submitType">确定</el-button>
        </template>
      </el-dialog>
      <el-dialog v-model="itemDialogVisible" :title="itemDialogType==='add'?'新增字典项':'编辑字典项'" :width="'80%'" style="max-width: 1200px">
        <el-form :model="itemForm" :rules="itemRules" ref="itemFormRef" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="显示文本" prop="label">
                <el-input v-model="itemForm.label" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选项值" prop="value">
                <el-input v-model="itemForm.value" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="排序" prop="sort_order">
                <el-input-number v-model="itemForm.sort_order" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="itemForm.status">
                  <el-option label="启用" :value="1" />
                  <el-option label="禁用" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="itemForm.remark" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="itemDialogVisible=false">取消</el-button>
          <el-button type="primary" @click="submitItem">确定</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getDictTypes, createDictType, updateDictType, deleteDictType,
  getDictItems, createDictItem, updateDictItem, deleteDictItem,
  exportDictTypesExcel, exportDictItemsExcel
} from '../api/dict'
import { Plus, Edit, Delete, Download } from '@element-plus/icons-vue'

const typeList = ref([])
const typeSearch = ref('')
const selectedTypeCode = ref(null)
const selectedTypeName = computed(() => {
  const t = typeList.value.find(t => t.code === selectedTypeCode.value)
  return t ? t.name : ''
})
const itemList = ref([])
const itemLoading = ref(false)

// 分页相关
const typePageSize = 10
const typeCurrentPage = ref(1)
const typeTotal = computed(() => filteredTypes.value.length)

// 类型弹窗
const typeDialogVisible = ref(false)
const typeDialogType = ref('add')
const typeForm = ref({ code: '', name: '', description: '' })
const typeFormRef = ref(null)
const typeRules = {
  code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
}

// 字典项弹窗
const itemDialogVisible = ref(false)
const itemDialogType = ref('add')
const itemForm = ref({ label: '', value: '', sort_order: 0, status: 1, remark: '' })
const itemFormRef = ref(null)
const itemRules = {
  label: [{ required: true, message: '请输入显示文本', trigger: 'blur' }],
  value: [{ required: true, message: '请输入选项值', trigger: 'blur' }]
}

const filteredTypes = computed(() => {
  if (!typeSearch.value) return typeList.value
  return typeList.value.filter(t => t.name.includes(typeSearch.value) || t.code.includes(typeSearch.value))
})

const pagedTypes = computed(() => {
  const start = (typeCurrentPage.value - 1) * typePageSize
  return filteredTypes.value.slice(start, start + typePageSize)
})

watch(typeSearch, () => {
  typeCurrentPage.value = 1 // 搜索时重置到第一页
})

function loadTypes() {
  getDictTypes().then(res => {
    typeList.value = res.data
    if (!typeList.value.find(t => t.code === selectedTypeCode.value)) {
      selectedTypeCode.value = typeList.value.length ? typeList.value[0].code : null
    }
    loadItems()
  })
}
function handleTypeSelect(code) {
  selectedTypeCode.value = code
  loadItems()
}
function showTypeDialog(type, row) {
  typeDialogType.value = type
  if (type === 'edit' && row) {
    typeForm.value = { ...row }
  } else {
    typeForm.value = { code: '', name: '', description: '' }
  }
  typeDialogVisible.value = true
}
function submitType() {
  typeFormRef.value.validate(async valid => {
    if (!valid) return
    if (typeDialogType.value === 'add') {
      await createDictType(typeForm.value)
      ElMessage.success('新增成功')
    } else {
      await updateDictType(typeForm.value.id, typeForm.value)
      ElMessage.success('修改成功')
    }
    typeDialogVisible.value = false
    loadTypes()
  })
}
function deleteType(row) {
  if (!row) return;
  ElMessageBox.confirm('确定删除该类型？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDictType(row.id).then(() => {
      ElMessage.success('删除成功');
      loadTypes();
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

function loadItems() {
  if (!selectedTypeCode.value) {
    itemList.value = []
    return
  }
  itemLoading.value = true
  getDictItems(selectedTypeCode.value).then(res => {
    itemList.value = res.data
  }).finally(() => {
    itemLoading.value = false
  })
}
function showItemDialog(type, row) {
  itemDialogType.value = type
  if (type === 'edit' && row) {
    itemForm.value = { ...row }
  } else {
    itemForm.value = { label: '', value: '', sort_order: 0, status: 1, remark: '' }
  }
  itemDialogVisible.value = true
}
function submitItem() {
  itemFormRef.value.validate(async valid => {
    if (!valid) return
    if (itemDialogType.value === 'add') {
      await createDictItem({ ...itemForm.value, type_code: selectedTypeCode.value })
      ElMessage.success('新增成功')
    } else {
      await updateDictItem(itemForm.value.id, itemForm.value)
      ElMessage.success('修改成功')
    }
    itemDialogVisible.value = false
    loadItems()
  })
}
function deleteItem(row) {
  if (!row) return;
  ElMessageBox.confirm('确定删除该字典项？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDictItem(row.id).then(() => {
      ElMessage.success('删除成功');
      loadItems();
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

// 字典项分页相关
const itemPageSize = ref(10)
const itemCurrentPage = ref(1)
const itemTotal = computed(() => itemList.value.length)
const pagedItemList = computed(() => {
  const start = (itemCurrentPage.value - 1) * itemPageSize.value
  return itemList.value.slice(start, start + itemPageSize.value)
})
function handleItemSizeChange(size) {
  itemPageSize.value = size
  itemCurrentPage.value = 1
}
function handleItemCurrentChange(page) {
  itemCurrentPage.value = page
}
watch(itemList, () => {
  itemCurrentPage.value = 1
})

const dictTypeWidth = ref(260)
let dragging = false
let startX = 0
let startWidth = 0
function startDrag(e) {
  dragging = true
  startX = e.clientX
  startWidth = dictTypeWidth.value
  document.body.style.cursor = 'col-resize'
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
}
function onDrag(e) {
  if (!dragging) return
  const delta = e.clientX - startX
  let newWidth = startWidth + delta
  if (newWidth < 180) newWidth = 180
  if (newWidth > 500) newWidth = 500
  dictTypeWidth.value = newWidth
}
function stopDrag() {
  dragging = false
  document.body.style.cursor = ''
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}

function handleExportDictTypesExcel() {
  exportDictTypesExcel().then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '字典类型.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
  })
}

function handleExportDictItemsExcel() {
  if (!selectedTypeCode.value) return;
  exportDictItemsExcel({ type_code: selectedTypeCode.value }).then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '字典项.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
  })
}

function handleExportAllDictItemsExcel() {
  exportDictItemsExcel().then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '全部字典项.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
  })
}

onMounted(() => {
  loadTypes()
})
</script>

<style scoped>
.dict-manage-container {
  background: #fff;
  min-height: 600px;
  height: 100%;
  width: 100%;
}
.drag-bar {
  position: absolute;
  top: 0;
  right: 0;
  width: 6px;
  height: 100%;
  cursor: col-resize;
  background: transparent;
  z-index: 10;
  transition: background 0.2s;
}
.drag-bar:hover {
  background: #e6e6e6;
}
.dict-type-list {
  background: #fff;
  border-right: 1px solid #ebeef5;
  padding: 24px;
  border-radius: 0;
  box-shadow: none;
  margin: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.dict-type-list-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.dict-type-title {
  font-size: 20px;
  font-weight: 600;
  color: #222;
  margin: 0;
  line-height: 1.3;
  flex: 1;
  text-align: left;
}
.dict-type-list-header .icon-button {
  padding: 0;
  width: 24px;
  height: 24px;
}
.dict-type-search {
  margin-bottom: 12px;
}
.dict-type-menu {
  background: transparent;
  min-height: 300px;
}
.dict-type-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px 8px 10px;
  border-radius: 7px;
  margin-bottom: 4px;
  border: 1px solid #e5e6eb;
  transition: background 0.2s, border 0.2s;
  position: relative;
  font-size: 14px;
  color: #222;
  cursor: pointer;
  min-height: 40px;
  height: 40px;
  box-sizing: border-box;
}
.dict-type-item:not(.is-active):hover {
  background: #f0f7ff;
  border: 1.5px solid #409eff;
}
.dict-type-item.is-active {
  background: linear-gradient(90deg, #e6f7ff 60%, #fafdff 100%);
  border: 2px solid #409eff;
  color: #1677ff;
  font-weight: bold;
}
.dict-type-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
}
.dict-type-code {
  font-size: 12px;
  color: #888;
  margin-left: 4px;
}
.dict-type-actions {
  display: flex;
  align-items: center;
  gap: 0px;
}
.dict-type-actions .el-button.el-button--text {
  padding: 0;
  min-width: 0;
}
.dict-type-actions .el-button:nth-child(2) {
  margin-left: 8px;
}
.dict-type-actions .el-button .el-icon {
  margin: 0;
}
.dict-type-empty {
  text-align: center;
  color: #bbb;
  padding: 32px 0 32px 0;
  font-size: 15px;
}
.dict-type-pagination {
  margin: 10px auto 0 auto;
  text-align: center;
}
.dict-item-list-container {
  flex: 1;
  padding: 24px;
  display: flex;
  flex-direction: column;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #222;
  line-height: 1.3;
}
.header-buttons {
  display: flex;
  align-items: center;
}
.header-buttons .el-button span {
  margin-left: 4px;
}
.pagination-container {
  margin-top: 0;
  display: flex;
  justify-content: flex-end;
  background: none;
  padding: 0;
  border: none;
}
:deep(.el-table th) {
  background-color: #F5F7FA !important;
  color: #606266 !important;
  font-weight: bold !important;
  font-size: 14px !important;
  border-bottom: 1px solid #ebeef5 !important;
}
:deep(.dict-item-list-container .el-table .el-table__cell) {
  font-size: 14px !important;
}
</style> 